﻿using System.Diagnostics;
using System.Numerics;
using System.Text;
using System.Timers;

namespace 考试监视器
{
    public class FolderMonitor
    {
        public bool status = false;
        private FileSystemWatcher _watcher;
        private string _logFilePath = "sdasdasd.txt";
        private string path = "";
        private string logMessage = "";

        public event EventHandler<FileChangedEventArgs> FileChanged;
        public event EventHandler<FileChangedEventArgs> FileCreated;
        public event EventHandler<FileChangedEventArgs> FileDeleted;
        public event EventHandler<FileChangedEventArgs> FileRenamed;
        private System.Timers.Timer _retryTimer;
        public void StartMonitoring(string path, string logMessage)
        {
            // 实例化FileSystemWatcher并设置属性
            this.path = path;
            _watcher = new FileSystemWatcher();
            _watcher.Path = path;
            _watcher.IncludeSubdirectories = true; // 监控子目录

            // 设置需要监控的事件类型
            _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;

            // 添加事件处理程序
            _watcher.Changed += OnFileChanged;
            _watcher.Created += OnFileCreated;
            _watcher.Deleted += OnFileDeleted;
            _watcher.Renamed += OnFileRenamed;
            _watcher.Error += ErrorDetected;
            // 将指定的消息写入日志文件
            LogToFile(logMessage);

            //设置错误处理
            _retryTimer = new System.Timers.Timer();
            _retryTimer.Elapsed += OnRetryTimerElapsed;

            // 开始监控
            _watcher.EnableRaisingEvents = true;
            status = true;
        }
        public void ReStartMonitoring()
        {
            // 实例化FileSystemWatcher并设置属性
            _watcher = new FileSystemWatcher();
            _watcher.Path = path;
            _watcher.IncludeSubdirectories = true; // 监控子目录

            // 设置需要监控的事件类型
            _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size;

            // 添加事件处理程序
            _watcher.Changed += OnFileChanged;
            _watcher.Created += OnFileCreated;
            _watcher.Deleted += OnFileDeleted;
            _watcher.Renamed += OnFileRenamed;
            _watcher.Error += ErrorDetected;
            // 将指定的消息写入日志文件
            LogToFile(logMessage);

            //设置错误处理
            _retryTimer = new System.Timers.Timer();
            _retryTimer.Elapsed += OnRetryTimerElapsed;

            // 开始监控
            _watcher.EnableRaisingEvents = true;
            Debug.WriteLine("重新开始监控");
            status = true;
        }


        private void ErrorDetected(object source, ErrorEventArgs e)
        {
            Debug.WriteLine($"Error detected: {e.GetException().Message}");
            // 停止当前的监控
            StopMonitoring();
            Thread.Sleep(10000);
            ReStartMonitoring();

        }
        public void StopMonitoring()
        {
            if (_watcher != null)
            {
                _watcher.Dispose();
                _watcher = null;
            }
            status = false;
        }

        private void OnFileChanged(object source, FileSystemEventArgs e)
        {
            LogToFile($"File changed: {e.FullPath}");
            FileChanged?.Invoke(this, new FileChangedEventArgs(e.FullPath));
        }

        private void OnFileCreated(object source, FileSystemEventArgs e)
        {
            LogToFile($"File created: {e.FullPath}");
            FileCreated?.Invoke(this, new FileChangedEventArgs(e.FullPath));
        }

        private void OnFileDeleted(object source, FileSystemEventArgs e)
        {
            LogToFile($"File deleted: {e.FullPath}");
            FileDeleted?.Invoke(this, new FileChangedEventArgs(e.FullPath));
        }

        private void OnFileRenamed(object source, RenamedEventArgs e)
        {
            LogToFile($"File renamed: {e.OldFullPath} -> {e.FullPath}");
            FileRenamed?.Invoke(this, new FileChangedEventArgs(e.FullPath));
        }

        static string StringToBinaryPlusOne(string input)
        {
            // 将字符串转换为字节
            byte[] bytes = Encoding.UTF8.GetBytes(input);

            // 将字节转换为二进制字符串
            string binaryString = string.Join("", bytes.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')));

            // 将二进制字符串转换为BigInteger，加一
            BigInteger binaryValue = new BigInteger(bytes.Reverse().ToArray());
            binaryValue += 12314;

            // 返回加一后的二进制字符串
            return binaryValue.ToString("X2");
        }

        private void LogToFile(string logMessage)
        {
            Debug.WriteLine(logMessage);
            try
            {
                using (StreamWriter writer = File.AppendText(_logFilePath))
                {
                    string inputstring = $"{DateTime.Now}: {logMessage}";
                    writer.WriteLine(StringToBinaryPlusOne(inputstring));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error writing to log file: {ex.Message}");
            }
        }
        private void OnRetryTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (Directory.Exists(_watcher.Path) && new DirectoryInfo(_watcher.Path).GetAccessControl().AreAccessRulesProtected == false)
            {
                try
                {
                    StartMonitoring(_watcher.Path, "");
                    Console.WriteLine("Monitoring resumed.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error restarting monitoring: {ex.Message}");
                }
                finally
                {
                    _retryTimer.Stop();
                }
            }
        }

    }

    public class FileChangedEventArgs : EventArgs
    {
        public string Path { get; }

        public FileChangedEventArgs(string path)
        {
            Path = path;
        }
    }
}
